package 回溯;


import java.util.ArrayList;
import java.util.List;

/**
 * https://leetcode.cn/problems/generate-parentheses/?favorite=2cktkvj
 *
 * 题解：https://mp.weixin.qq.com/s?__biz=MzAxODQxMDM0Mw==&mid=2247493569&idx=1&sn=c6d826b43c0aa2534ab207119d8bcba5&chksm=9bd419c9aca390df323169476b6288b9fc6907fa984c02324ad7400e30184dd0451ba0d0d5fb&scene=178&cur_album_id=2165135739779448832#rd
 */
public class _22_括号生成 {


    List<String> result;

    List<Character> res;

    int n;

    public List<String> generateParenthesis(int n) {
        this.result = new ArrayList<>();
        this.res = new ArrayList<>();
        this.n = n;

        dfs(n, n);
        return result;
    }


    private void dfs(int left, int right) {
        if (left == 0 && right == 0) {
            char[] list = new char[2 * n];
            for (int i = 0; i < res.size(); i++) {
                list[i] = res.get(i);
            }
            result.add(new String(list));
            return;
        }

        if (left > right) return;

        if (left < 0 || right < 0) return;

        res.add('(');
        dfs(left - 1, right);
        res.remove(res.size() - 1);

        res.add(')');
        dfs(left, right - 1);
        res.remove(res.size() - 1);
    }
}
